package com.awesome.common.util.crash

import android.content.Context
import android.os.Looper
import android.os.SystemClock
import android.widget.Toast
import com.awesome.common.util.ActivityManager
import java.io.File
import java.io.IOException
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.*
import kotlin.system.exitProcess


/**
 * Author: JFangZ
 * Email: janezhang1901@163.com
 * Date: 2020-02-11 21:02
 * Description:全局异常处理类
 */
enum class CrashHandler : Thread.UncaughtExceptionHandler {
    SINGLETON;

    companion object {
        private const val TAG = "CrashHandler"
    }

    private var context: Context? = null
    private var uncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null

    override fun uncaughtException(t: Thread, e: Throwable) {
        if (!handleException(e) && uncaughtExceptionHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            uncaughtExceptionHandler?.uncaughtException(t, e);
        } else {
            SystemClock.sleep(2000)
            // 退出程序
            ActivityManager.exit()
            android.os.Process.killProcess(android.os.Process.myPid());
            exitProcess(1);
        }
    }


    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2021/4/13 18:38
     * Description:Handle exception,toast and save log.
     */
    private fun handleException(throwable: Throwable): Boolean {
        throwable.printStackTrace()
        // 使用Toast来显示异常信息
        object : Thread() {
            override fun run() {
                Looper.prepare()
                Toast.makeText(context, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show()
                Looper.loop()
                Looper.myLooper()?.quit()
            }
        }.start()
        try {
            save2File(throwable)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return true
    }

    private fun save2File(throwable: Throwable) {
        val dateTime: String = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINA).format(Date(System.currentTimeMillis()))
        val file: File
//        if (PermissionUtil.isGranted(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//            // 有存储卡权限
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                // 并且 SDK version 在 23 及以上,存到内部存储里
//                file = File(context?.getExternalFilesDir(null)?.absolutePath
//                        + File.separator
//                        + "log"
//                        + File.separator
//                        + dateTime
//                        + ".log")
//            } else {
//                // 小于 23 就存到 SD 卡里
//                file = File(Environment.getExternalStorageDirectory()?.absolutePath
//                        + File.separator
//                        + context?.packageName
//                        + "log"
//                        + File.separator
//                        + dateTime
//                        + ".log")
//            }
//        } else {
            // 没有存储卡权限就存到内部存储里
            file = File(context?.cacheDir?.absolutePath
                    + File.separator
                    + "log"
                    + File.separator
                    + dateTime
                    + ".log")
//        }
        if (!file.parentFile!!.exists()) {
            file.parentFile!!.mkdirs()
        }
        file.createNewFile()
        val printWriter = PrintWriter(file)
        throwable.printStackTrace(printWriter)
        printWriter.close()
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020-02-11 21:49
     * Description:Init exception handler,exit app graceful and save log.
     */
    fun init(context: Context) {
        this.context = context
        // 获取程序默认的 Exception 处理器
        uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
        // 将程序默认的 Exception 处理器设置为该对象
        Thread.setDefaultUncaughtExceptionHandler(this)
    }
}
